import json
import requests
import re


def fetch_page(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.text
    except requests.RequestException as e:
        print(f"请求页面失败: {e}")
        return None


def extract_json_data(page_text):
    try:
        json_match = re.search(r'window.__INITIAL_DATA__ =(.*?)</script>', page_text)
        if json_match:
            json_str = json_match.group(1)
            json_str = re.sub(r'undefined', 'null', json_str)
            return json.loads(json_str)
        else:
            print("未找到JSON数据")
            return None
    except json.JSONDecodeError as e:
        print(f"解析JSON数据失败: {e}")
        return None


def print_song_info(json_data):
    if json_data and 'songInfoList' in json_data:
        for song in json_data['songInfoList']:
            print(song)
    else:
        print("未找到歌曲信息")


def main():
    url = "https://y.qq.com/n/ryqq/toplist/26"
    page_text = fetch_page(url)
    if page_text:
        json_data = extract_json_data(page_text)
        if json_data:
            print_song_info(json_data)


if __name__ == "__main__":
    main()
